// 初始化
document.addEventListener('DOMContentLoaded', async () => {
  await loadSettings();
  await updatePlatformStatus();
  await updateStats();
  
  // 绑定事件
  bindEvents();
  
  // 定时更新状态
  setInterval(updatePlatformStatus, 5000);
});

// 加载设置
async function loadSettings() {
  const settings = await chrome.storage.sync.get({
    backendUrl: 'http://localhost:8080',
    autoCollect: true,
    syncToBackend: true,
    stableWaitTime: 2,
    platformSwitchDelay: 8
  });
  
  document.getElementById('backend-url').value = settings.backendUrl;
  document.getElementById('auto-collect').checked = settings.autoCollect;
  document.getElementById('sync-to-backend').checked = settings.syncToBackend;
  document.getElementById('stable-wait-time').value = settings.stableWaitTime;
  document.getElementById('platform-switch-delay').value = settings.platformSwitchDelay;
}

// 更新平台状态
async function updatePlatformStatus() {
  const platforms = ['deepseek', 'yuanbao', 'doubao'];
  
  for (const platform of platforms) {
    const status = await checkPlatformStatus(platform);
    updateStatusIndicator(platform, status);
  }
}

// 检查平台状态
async function checkPlatformStatus(platform) {
  try {
    // 查询对应平台的标签页
    const tabs = await chrome.tabs.query({});
    const platformUrls = {
      'deepseek': 'chat.deepseek.com',
      'yuanbao': 'yuanbao.tencent.com',
      'doubao': 'doubao.com'
    };
    
    const platformTab = tabs.find(tab => 
      tab.url && tab.url.includes(platformUrls[platform])
    );
    
    if (platformTab) {
      // 发送消息检查登录状态
      try {
        const response = await chrome.tabs.sendMessage(platformTab.id, {
          action: 'checkLoginStatus'
        });
        return response.loggedIn ? 'online' : 'offline';
      } catch (e) {
        return 'unknown';
      }
    }
    
    return 'offline';
  } catch (e) {
    return 'unknown';
  }
}

// 更新状态指示器
function updateStatusIndicator(platform, status) {
  const statusText = {
    'online': '已登录',
    'offline': '未登录',
    'unknown': '未打开'
  };
  
  const indicator = document.querySelector(`#${platform}-status .status-indicator`);
  if (indicator) {
    indicator.setAttribute('data-status', status);
    indicator.textContent = statusText[status];
  }
}

// 更新统计信息
async function updateStats() {
  const stats = await chrome.storage.local.get({
    todayCount: 0,
    totalCount: 0,
    cachedData: []
  });
  
  document.getElementById('today-count').textContent = stats.todayCount;
  document.getElementById('total-count').textContent = stats.totalCount;
  document.getElementById('cache-count').textContent = stats.cachedData.length;
}

// 绑定事件
function bindEvents() {
  // 快速发送
  document.getElementById('send-btn').addEventListener('click', handleQuickSend);
  
  // 批量发送
  document.getElementById('batch-send-btn').addEventListener('click', handleBatchSend);
  
  // 保存设置
  document.getElementById('save-settings-btn').addEventListener('click', handleSaveSettings);
  
  // 查看数据
  document.getElementById('view-data-btn').addEventListener('click', handleViewData);
  
  // 多平台对比
  document.getElementById('comparison-btn').addEventListener('click', handleShowComparison);
  
  // 导出数据
  document.getElementById('export-json-btn').addEventListener('click', () => handleExportData('json'));
  document.getElementById('export-csv-btn').addEventListener('click', () => handleExportData('csv'));
  document.getElementById('export-html-btn').addEventListener('click', () => handleExportData('html'));
  
  // 对比视图控制
  document.getElementById('show-only-multi').addEventListener('change', handleShowComparison);
  document.getElementById('refresh-comparison-btn').addEventListener('click', handleShowComparison);
  
  // 清除缓存
  document.getElementById('clear-cache-btn').addEventListener('click', handleClearCache);
  
  // 任务管理 ⭐ 新增
  document.getElementById('refresh-tasks-btn').addEventListener('click', refreshTasks);
  document.getElementById('execute-task-btn').addEventListener('click', executeTask);
}

// 处理快速发送
async function handleQuickSend() {
  const message = document.getElementById('quick-message').value.trim();
  if (!message) {
    alert('请输入消息');
    return;
  }
  
  const checkboxes = document.querySelectorAll('.platform-select input:checked');
  const platforms = Array.from(checkboxes).map(cb => cb.value);
  
  if (platforms.length === 0) {
    alert('请选择至少一个平台');
    return;
  }
  
  // 发送到后台处理
  chrome.runtime.sendMessage({
    action: 'sendToMultiplePlatforms',
    message: message,
    platforms: platforms
  }, (response) => {
    if (response.success) {
      alert('消息已发送到所有平台');
      document.getElementById('quick-message').value = '';
    } else {
      alert('发送失败: ' + response.error);
    }
  });
}

// 处理批量发送
async function handleBatchSend() {
  const batchText = document.getElementById('batch-messages').value.trim();
  if (!batchText) {
    alert('请输入问题列表');
    return;
  }
  
  const messages = batchText.split('\n').filter(m => m.trim());
  if (messages.length === 0) {
    alert('没有有效的问题');
    return;
  }
  
  const checkboxes = document.querySelectorAll('.platform-select input:checked');
  const platforms = Array.from(checkboxes).map(cb => cb.value);
  
  // 显示进度
  const progressDiv = document.getElementById('batch-progress');
  progressDiv.style.display = 'block';
  
  const progressFill = document.getElementById('progress-fill');
  const progressText = document.getElementById('progress-text');
  
  let completed = 0;
  const total = messages.length * platforms.length;
  
  progressText.textContent = `0/${total}`;
  progressFill.style.width = '0%';
  
  // 发送到后台处理
  chrome.runtime.sendMessage({
    action: 'batchSend',
    messages: messages,
    platforms: platforms
  });
  
  // 监听进度更新
  const listener = (message) => {
    if (message.action === 'batchProgress') {
      completed++;
      const progress = (completed / total) * 100;
      progressFill.style.width = progress + '%';
      progressText.textContent = `${completed}/${total}`;
      
      if (completed >= total) {
        chrome.runtime.onMessage.removeListener(listener);
        setTimeout(() => {
          progressDiv.style.display = 'none';
          alert('批量发送完成！');
        }, 1000);
      }
    }
  };
  
  chrome.runtime.onMessage.addListener(listener);
}

// 保存设置
async function handleSaveSettings() {
  const stableWaitTime = parseInt(document.getElementById('stable-wait-time').value) || 2;
  const platformSwitchDelay = parseInt(document.getElementById('platform-switch-delay').value) || 8;
  
  const settings = {
    backendUrl: document.getElementById('backend-url').value,
    autoCollect: document.getElementById('auto-collect').checked,
    syncToBackend: document.getElementById('sync-to-backend').checked,
    stableWaitTime: stableWaitTime,
    platformSwitchDelay: platformSwitchDelay
  };
  
  await chrome.storage.sync.set(settings);
  
  // 通知所有content script重新加载配置
  const tabs = await chrome.tabs.query({});
  for (const tab of tabs) {
    try {
      await chrome.tabs.sendMessage(tab.id, { 
        action: 'updateSettings', 
        settings 
      });
    } catch (e) {
      // 某些标签页可能无法接收消息，忽略错误
    }
  }
  
  alert('设置已保存');
}

// 查看数据
async function handleViewData() {
  const data = await chrome.storage.local.get('cachedData');
  const cachedData = data.cachedData || [];
  
  const dataViewer = document.getElementById('data-viewer');
  const dataList = document.getElementById('data-list');
  
  // 切换显示/隐藏
  if (dataViewer.style.display === 'none') {
    dataViewer.style.display = 'block';
    
    // 显示数据
    if (cachedData.length === 0) {
      dataList.innerHTML = `
        <div class="no-data">
          <div class="no-data-icon">📭</div>
          <div>暂无采集数据</div>
          <div style="font-size: 12px; margin-top: 8px;">
            在AI平台正常对话，插件会自动采集数据
          </div>
        </div>
      `;
    } else {
      // 显示最近10条数据（倒序）
      const recentData = cachedData.slice(-10).reverse();
      
      dataList.innerHTML = recentData.map(item => `
        <div class="data-item">
          <div class="data-header">
            <span class="data-platform">${item.platform || '未知'}</span>
            <span class="data-time">${formatTime(item.timestamp)}</span>
          </div>
          <div class="data-question">
            <div class="data-question-label">问题：</div>
            ${escapeHtml(item.userMessage || '')}
          </div>
          <div class="data-answer">
            <div class="data-answer-label">回答：</div>
            ${item.answerHTML || escapeHtml(item.answer || item.aiResponse || '')}
          </div>
        </div>
      `).join('');
    }
    
    // 修改按钮文字
    document.getElementById('view-data-btn').textContent = '隐藏采集数据';
  } else {
    dataViewer.style.display = 'none';
    document.getElementById('view-data-btn').textContent = '查看采集数据';
  }
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return '未知时间';
  
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;
  
  // 如果是今天
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 如果是近期
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    return date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  }
  
  return date.toLocaleDateString('zh-CN');
}

// HTML转义
function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

// 导出数据
async function handleExportData(format = 'json') {
  const data = await chrome.storage.local.get('cachedData');
  const cachedData = data.cachedData || [];
  
  if (cachedData.length === 0) {
    alert('没有数据可导出');
    return;
  }
  
  let content, mimeType, extension;
  
  switch (format) {
    case 'json':
      content = JSON.stringify(cachedData, null, 2);
      mimeType = 'application/json';
      extension = 'json';
      break;
      
    case 'csv':
      content = exportToCSV(cachedData);
      mimeType = 'text/csv;charset=utf-8;';
      extension = 'csv';
      break;
      
    case 'html':
      content = exportToHTML(cachedData);
      mimeType = 'text/html;charset=utf-8;';
      extension = 'html';
      break;
      
    default:
      alert('不支持的导出格式');
      return;
  }
  
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  
  const a = document.createElement('a');
  a.href = url;
  a.download = `ai-crawler-data-${Date.now()}.${extension}`;
  a.click();
  
  URL.revokeObjectURL(url);
  
  alert(`已导出 ${cachedData.length} 条数据为 ${format.toUpperCase()} 格式`);
}

// 导出为CSV
function exportToCSV(data) {
  const headers = ['平台', '问题', '回答', '时间'];
  const rows = data.map(item => [
    item.platform || '',
    `"${(item.question || '').replace(/"/g, '""')}"`,
    `"${(item.answer || '').replace(/"/g, '""')}"`,
    new Date(item.timestamp).toLocaleString('zh-CN')
  ]);
  
  return [headers.join(','), ...rows.map(row => row.join(','))].join('\n');
}

// 导出为HTML
function exportToHTML(data) {
  // 按问题分组
  const grouped = groupByQuestion(data);
  
  const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI平台对话记录 - ${new Date().toLocaleDateString('zh-CN')}</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      line-height: 1.6;
      color: #202124;
      background: #f8f9fa;
      padding: 20px;
    }
    
    .container {
      max-width: 1200px;
      margin: 0 auto;
      background: white;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    
    h1 {
      color: #1a73e8;
      margin-bottom: 10px;
      font-size: 28px;
    }
    
    .meta {
      color: #5f6368;
      margin-bottom: 30px;
      font-size: 14px;
    }
    
    .stats {
      background: #e8f0fe;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 30px;
      display: flex;
      gap: 30px;
    }
    
    .stat-item {
      font-size: 14px;
    }
    
    .stat-value {
      font-weight: 600;
      color: #1a73e8;
      font-size: 20px;
    }
    
    .comparison-group {
      background: #fff;
      border: 1px solid #dadce0;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 24px;
    }
    
    .question {
      background: #e8f0fe;
      padding: 16px;
      border-radius: 6px;
      margin-bottom: 20px;
      font-weight: 500;
      color: #1967d2;
      font-size: 16px;
    }
    
    .platforms {
      display: grid;
      gap: 16px;
    }
    
    .platform-response {
      background: #f8f9fa;
      border-left: 4px solid #1a73e8;
      border-radius: 4px;
      padding: 16px;
    }
    
    .platform-response.deepseek {
      border-left-color: #1a73e8;
    }
    
    .platform-response.yuanbao {
      border-left-color: #34a853;
    }
    
    .platform-response.doubao {
      border-left-color: #ea4335;
    }
    
    .platform-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
    }
    
    .platform-name {
      font-weight: 600;
      font-size: 14px;
    }
    
    .platform-name.deepseek {
      color: #1a73e8;
    }
    
    .platform-name.yuanbao {
      color: #34a853;
    }
    
    .platform-name.doubao {
      color: #ea4335;
    }
    
    .platform-time {
      font-size: 12px;
      color: #5f6368;
    }
    
    .platform-answer {
      background: white;
      padding: 12px;
      border-radius: 4px;
      font-size: 14px;
      line-height: 1.8;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
    
    .single-platform {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
    }
    
    .single-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
    }
    
    .single-question {
      background: white;
      padding: 12px;
      border-radius: 4px;
      margin-bottom: 12px;
      font-size: 14px;
      color: #1967d2;
      font-weight: 500;
    }
    
    .single-answer {
      background: white;
      padding: 12px;
      border-radius: 4px;
      font-size: 14px;
      line-height: 1.8;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
    
    /* HTML内容格式支持 */
    .platform-answer table,
    .single-answer table {
      border-collapse: collapse;
      width: 100%;
      margin: 12px 0;
      font-size: 13px;
    }
    
    .platform-answer th,
    .platform-answer td,
    .single-answer th,
    .single-answer td {
      border: 1px solid #dadce0;
      padding: 8px 10px;
      text-align: left;
    }
    
    .platform-answer th,
    .single-answer th {
      background: #e8f0fe;
      font-weight: 600;
      color: #1967d2;
    }
    
    .platform-answer ul,
    .platform-answer ol,
    .single-answer ul,
    .single-answer ol {
      margin: 10px 0;
      padding-left: 30px;
    }
    
    .platform-answer li,
    .single-answer li {
      margin: 6px 0;
      line-height: 1.6;
    }
    
    .platform-answer h3,
    .platform-answer h4,
    .single-answer h3,
    .single-answer h4 {
      margin: 16px 0 8px 0;
      color: #1a73e8;
      font-weight: 600;
    }
    
    .platform-answer p,
    .single-answer p {
      margin: 8px 0;
      line-height: 1.8;
    }
    
    .platform-answer strong,
    .single-answer strong {
      font-weight: 600;
      color: #202124;
    }
    
    .platform-answer code,
    .single-answer code {
      background: #f8f9fa;
      padding: 2px 6px;
      border-radius: 3px;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      font-size: 13px;
    }
    
    @media print {
      body {
        background: white;
        padding: 0;
      }
      
      .container {
        box-shadow: none;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>🤖 AI平台对话记录</h1>
    <div class="meta">
      导出时间：${new Date().toLocaleString('zh-CN')}
    </div>
    
    <div class="stats">
      <div class="stat-item">
        <div>总对话数</div>
        <div class="stat-value">${data.length}</div>
      </div>
      <div class="stat-item">
        <div>多平台对比</div>
        <div class="stat-value">${Object.keys(grouped.multi).length}</div>
      </div>
      <div class="stat-item">
        <div>单平台记录</div>
        <div class="stat-value">${grouped.single.length}</div>
      </div>
    </div>
    
    ${Object.keys(grouped.multi).length > 0 ? `
    <h2 style="margin-bottom: 20px; color: #1a73e8;">📊 多平台对比</h2>
    ${Object.entries(grouped.multi).map(([question, platforms]) => `
      <div class="comparison-group">
        <div class="question">❓ ${escapeHtml(question)}</div>
        <div class="platforms">
          ${Object.entries(platforms).map(([platform, item]) => `
            <div class="platform-response ${platform}">
              <div class="platform-header">
                <span class="platform-name ${platform}">${getPlatformDisplayName(platform)}</span>
                <span class="platform-time">${new Date(item.timestamp).toLocaleString('zh-CN')}</span>
              </div>
              <div class="platform-answer">${item.answerHTML || escapeHtml(item.answer)}</div>
            </div>
          `).join('')}
        </div>
      </div>
    `).join('')}
    ` : ''}
    
    ${grouped.single.length > 0 ? `
    <h2 style="margin: 30px 0 20px; color: #1a73e8;">📝 单平台记录</h2>
    ${grouped.single.map(item => `
      <div class="single-platform">
        <div class="single-header">
          <span class="platform-name ${item.platform}">${getPlatformDisplayName(item.platform)}</span>
          <span class="platform-time">${new Date(item.timestamp).toLocaleString('zh-CN')}</span>
        </div>
        <div class="single-question">❓ ${escapeHtml(item.question)}</div>
        <div class="single-answer">${item.answerHTML || escapeHtml(item.answer)}</div>
      </div>
    `).join('')}
    ` : ''}
  </div>
</body>
</html>`;
  
  return html;
}

// 按问题分组
function groupByQuestion(data) {
  const multi = {};  // 多平台数据
  const single = []; // 单平台数据
  const questionMap = new Map();
  
  // 第一遍：收集所有问题及其平台
  data.forEach(item => {
    const q = normalizeQuestion(item.question);
    if (!questionMap.has(q)) {
      questionMap.set(q, []);
    }
    questionMap.get(q).push(item);
  });
  
  // 第二遍：分类
  questionMap.forEach((items, question) => {
    if (items.length > 1) {
      // 多平台
      multi[question] = {};
      items.forEach(item => {
        multi[question][item.platform] = item;
      });
    } else {
      // 单平台
      single.push(items[0]);
    }
  });
  
  return { multi, single };
}

// 标准化问题（去除空白、标点等）
function normalizeQuestion(question) {
  if (!question) return '';
  return question.trim().toLowerCase()
    .replace(/[？?！!。.，,；;：:、\s]/g, '');
}

// 获取平台显示名称
function getPlatformDisplayName(platform) {
  const names = {
    'deepseek': 'DeepSeek',
    'yuanbao': '元宝',
    'doubao': '豆包'
  };
  return names[platform] || platform;
}

// 显示多平台对比
async function handleShowComparison() {
  const data = await chrome.storage.local.get('cachedData');
  const cachedData = data.cachedData || [];
  
  const comparisonViewer = document.getElementById('comparison-viewer');
  const dataViewer = document.getElementById('data-viewer');
  const comparisonList = document.getElementById('comparison-list');
  const showOnlyMulti = document.getElementById('show-only-multi').checked;
  
  // 隐藏普通数据查看器
  dataViewer.style.display = 'none';
  document.getElementById('view-data-btn').textContent = '查看采集数据';
  
  // 切换显示/隐藏
  if (comparisonViewer.style.display === 'none') {
    comparisonViewer.style.display = 'block';
    document.getElementById('comparison-btn').textContent = '📊 关闭对比';
    
    // 显示对比数据
    if (cachedData.length === 0) {
      comparisonList.innerHTML = `
        <div class="no-data">
          <div class="no-data-icon">📭</div>
          <p>暂无数据</p>
        </div>
      `;
      return;
    }
    
    const grouped = groupByQuestion(cachedData);
    const multiEntries = Object.entries(grouped.multi);
    
    if (showOnlyMulti && multiEntries.length === 0) {
      comparisonList.innerHTML = `
        <div class="no-data">
          <div class="no-data-icon">📊</div>
          <p>暂无多平台对比数据</p>
          <p style="font-size: 12px; margin-top: 8px;">
            请发送相同的问题到多个平台
          </p>
        </div>
      `;
      return;
    }
    
    let html = '';
    
    // 显示多平台对比
    if (multiEntries.length > 0) {
      html += multiEntries.map(([question, platforms]) => {
        const platformEntries = Object.entries(platforms);
        return `
          <div class="comparison-group">
            <div class="comparison-question">❓ ${escapeHtml(question)}</div>
            <div class="comparison-platforms">
              ${platformEntries.map(([platform, item]) => `
              <div class="platform-response ${platform}">
                <div class="platform-response-header">
                  <span class="platform-response-name">${getPlatformDisplayName(platform)}</span>
                  <span class="platform-response-time">${formatTime(item.timestamp)}</span>
                </div>
                <div class="platform-response-content">${item.answerHTML || escapeHtml(item.answer)}</div>
              </div>
              `).join('')}
            </div>
            <div class="comparison-meta">
              <span>对比平台: ${platformEntries.length}</span>
              <span>总字数: ${platformEntries.reduce((sum, [_, item]) => sum + (item.answer?.length || 0), 0)}</span>
            </div>
          </div>
        `;
      }).join('');
    }
    
    // 显示单平台数据（如果未勾选"只显示多平台"）
    if (!showOnlyMulti && grouped.single.length > 0) {
      html += `
        <h3 style="margin: 24px 0 12px; color: #5f6368; font-size: 14px;">
          单平台记录 (${grouped.single.length})
        </h3>
      `;
      html += grouped.single.slice(0, 10).map(item => `
        <div class="comparison-group">
          <div class="comparison-question">❓ ${escapeHtml(item.question)}</div>
          <div class="comparison-platforms">
            <div class="platform-response ${item.platform}">
              <div class="platform-response-header">
                <span class="platform-response-name">${getPlatformDisplayName(item.platform)}</span>
                <span class="platform-response-time">${formatTime(item.timestamp)}</span>
              </div>
              <div class="platform-response-content">${item.answerHTML || escapeHtml(item.answer)}</div>
            </div>
          </div>
        </div>
      `).join('');
      
      if (grouped.single.length > 10) {
        html += `
          <div style="text-align: center; color: #5f6368; font-size: 12px; margin-top: 12px;">
            还有 ${grouped.single.length - 10} 条记录未显示
          </div>
        `;
      }
    }
    
    comparisonList.innerHTML = html;
  } else {
    comparisonViewer.style.display = 'none';
    document.getElementById('comparison-btn').textContent = '📊 多平台对比';
  }
}

// 清除缓存
async function handleClearCache() {
  if (confirm('确定要清除所有缓存数据吗？')) {
    await chrome.storage.local.set({
      cachedData: [],
      todayCount: 0
    });
    await updateStats();
    alert('缓存已清除');
  }
}

// ============================================================================
// 任务管理功能 ⭐ 新增
// ============================================================================

let currentPendingTask = null; // 当前待执行的任务

/**
 * 刷新待执行任务
 */
async function refreshTasks() {
  const settings = await chrome.storage.sync.get({ backendUrl: 'http://localhost:8080' });
  const apiBaseUrl = settings.backendUrl + '/api';

  try {
    console.log('[refreshTasks] 开始刷新任务列表...');
    
    // 获取所有待执行和执行中的任务
    const response = await fetch(`${apiBaseUrl}/collect-tasks?status=pending&size=100`);
    const result = await response.json();

    if (result.code !== 200) {
      throw new Error(result.message || '获取任务失败');
    }

    const tasks = result.data.list || [];
    console.log(`[refreshTasks] 获取到 ${tasks.length} 个待执行任务`);
    
    // 更新任务数量
    document.getElementById('pending-task-count').textContent = tasks.length;
    
    if (tasks.length > 0) {
      // 显示任务列表
      renderTaskList(tasks);
      
      // 显示任务列表容器
      document.getElementById('task-list-container').style.display = 'block';
      
      alert(`✅ 成功加载 ${tasks.length} 个待执行任务\n请从列表中选择要执行的任务`);
    } else {
      // 隐藏任务列表
      document.getElementById('task-list-container').style.display = 'none';
      
      // 重置选中任务
      currentPendingTask = null;
      updateSelectedTaskInfo(null);
      document.getElementById('execute-task-btn').disabled = true;
      
      alert('暂无待执行任务');
    }
  } catch (error) {
    console.error('[refreshTasks] 刷新任务失败:', error);
    alert('刷新任务失败: ' + error.message);
  }
}

/**
 * 渲染任务列表
 */
function renderTaskList(tasks) {
  const taskListEl = document.getElementById('task-list');
  taskListEl.innerHTML = '';
  
  tasks.forEach((task, index) => {
    const taskItem = document.createElement('div');
    taskItem.className = 'task-item-card';
    taskItem.dataset.taskId = task.taskId;
    
    // 构建任务卡片HTML
    taskItem.innerHTML = `
      <div class="task-item-header">
        <span class="task-item-name">${task.taskName}</span>
        <span class="task-item-badge">${getStatusText(task.taskStatus)}</span>
      </div>
      <div class="task-item-details">
        <div class="task-item-detail">
          <span class="detail-icon">📝</span>
          <span>${task.totalQuestionCount || 0} 个问句</span>
        </div>
        <div class="task-item-detail">
          <span class="detail-icon">🌐</span>
          <span>${task.totalPlatformCount || 0} 个平台</span>
        </div>
        <div class="task-item-detail">
          <span class="detail-icon">📊</span>
          <span>进度 ${task.progressCompleted || 0}/${task.totalCollectCount || 0} (${(task.progressPercentage || 0).toFixed(0)}%)</span>
        </div>
      </div>
      <div class="task-item-meta">
        <span>ID: ${task.taskId}</span>
        <span>${formatDate(task.createTime)}</span>
      </div>
    `;
    
    // 点击选中任务
    taskItem.addEventListener('click', () => {
      selectTask(task, taskItem);
    });
    
    taskListEl.appendChild(taskItem);
  });
  
  console.log(`[renderTaskList] 渲染了 ${tasks.length} 个任务`);
}

/**
 * 选中任务
 */
function selectTask(task, taskItemEl) {
  console.log(`[selectTask] 选中任务: ${task.taskName} (ID: ${task.taskId})`);
  
  // 移除所有任务的选中状态
  document.querySelectorAll('.task-item-card').forEach(item => {
    item.classList.remove('selected');
  });
  
  // 设置当前任务为选中状态
  taskItemEl.classList.add('selected');
  
  // 保存选中的任务
  currentPendingTask = task;
  
  // 更新选中任务信息
  updateSelectedTaskInfo(task);
  
  // 启用执行按钮
  document.getElementById('execute-task-btn').disabled = false;
}

/**
 * 更新选中任务信息
 */
function updateSelectedTaskInfo(task) {
  if (task) {
    document.getElementById('selected-task-name').textContent = task.taskName;
    document.getElementById('selected-task-questions').textContent = task.totalQuestionCount || 0;
    document.getElementById('selected-task-platforms').textContent = task.totalPlatformCount || 0;
  } else {
    document.getElementById('selected-task-name').textContent = '未选择';
    document.getElementById('selected-task-questions').textContent = '0';
    document.getElementById('selected-task-platforms').textContent = '0';
  }
}

/**
 * 获取状态文本
 */
function getStatusText(status) {
  const statusMap = {
    'pending': '待执行',
    'running': '执行中',
    'completed': '已完成',
    'failed': '失败',
    'cancelled': '已取消'
  };
  return statusMap[status] || status;
}

/**
 * 格式化日期
 */
function formatDate(dateString) {
  if (!dateString) return '';
  const date = new Date(dateString);
  const now = new Date();
  const diff = now - date;
  
  // 小于1分钟
  if (diff < 60000) {
    return '刚刚';
  }
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  }
  // 小于1天
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  }
  // 大于1天
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  return `${month}月${day}日 ${hour}:${minute.toString().padStart(2, '0')}`;
}

/**
 * 执行任务（支持断点续传）
 * ⭐⭐⭐ 改为调用background script执行，避免popup关闭导致任务中断 ⭐⭐⭐
 */
async function executeTask() {
  if (!currentPendingTask) {
    alert('请先刷新任务');
    return;
  }

  const taskId = currentPendingTask.taskId;

  console.log(`\n[Popup] ========== 触发任务执行 ${taskId} ==========`);
  console.log(`[Popup] 任务名称: ${currentPendingTask.taskName}`);
  console.log(`[Popup] ⭐ 任务将在background script中执行，不受popup关闭影响`);

  // 禁用按钮
  document.getElementById('execute-task-btn').disabled = true;
  document.getElementById('execute-task-btn').textContent = '执行中...';
  
  try {
    console.log(`[Popup] 发送消息给background script...`);
    
    // ⭐⭐⭐ 发送消息给background script执行任务 ⭐⭐⭐
    chrome.runtime.sendMessage({
      action: 'executeTask',
      taskId: taskId
    }, (response) => {
      console.log(`[Popup] 收到background响应:`, response);
      
      if (chrome.runtime.lastError) {
        console.error(`[Popup] ❌ runtime错误:`, chrome.runtime.lastError);
        alert('任务执行失败: ' + chrome.runtime.lastError.message);
        document.getElementById('execute-task-btn').disabled = false;
        document.getElementById('execute-task-btn').textContent = '执行任务';
        return;
      }
      
      if (response && response.success) {
        console.log(`[Popup] ✅ 任务执行成功`);
        alert(`任务执行完成！\n${response.message || ''}\n\n提示：任务在后台执行，popup可以关闭。`);
        
        // 重置状态
        currentPendingTask = null;
        document.getElementById('current-task-name').textContent = '-';
        document.getElementById('execute-task-btn').textContent = '执行任务';
        
        // 刷新任务列表
        setTimeout(() => {
          refreshTasks();
        }, 1000);
      } else {
        console.error(`[Popup] ❌ 任务执行失败:`, response);
        alert('任务执行失败: ' + (response ? response.error : '未知错误'));
        document.getElementById('execute-task-btn').disabled = false;
        document.getElementById('execute-task-btn').textContent = '执行任务';
      }
    });
    
    console.log(`[Popup] ✅ 消息已发送，任务在后台执行...`);
    console.log(`[Popup] 💡 你现在可以关闭popup窗口，任务会继续在后台执行`);
    
  } catch (error) {
    console.error('[Popup] 触发任务执行失败:', error);
    alert('任务执行失败: ' + error.message);
    
    // 重置按钮
    document.getElementById('execute-task-btn').disabled = false;
    document.getElementById('execute-task-btn').textContent = '执行任务';
  }
}

/**
 * ⭐ 以下是旧的executeTask逻辑，已迁移到background script
 * 保留作为参考，不再使用
 */
async function executeTask_OLD() {
  if (!currentPendingTask) {
    alert('请先刷新任务');
    return;
  }

  const taskId = currentPendingTask.taskId;
  const settings = await chrome.storage.sync.get({ backendUrl: 'http://localhost:8080' });
  const apiBaseUrl = settings.backendUrl + '/api';

  try {
    // 1. 获取待执行的问句列表（断点续传）
    console.log(`\n========== 开始执行任务 ${taskId} ==========`);
    console.log(`请求URL: ${apiBaseUrl}/collect-tasks/${taskId}/pending-questions`);
    
    const response = await fetch(`${apiBaseUrl}/collect-tasks/${taskId}/pending-questions`);
    const result = await response.json();
    
    console.log('待执行问句API响应:', result);
    console.log('响应code:', result.code);
    console.log('响应data:', result.data);

    if (result.code !== 200) {
      throw new Error(result.message || '获取待执行问句失败');
    }

    const { taskName, pendingQuestions } = result.data;
    
    console.log('任务名称:', taskName);
    console.log('待执行问句列表:', pendingQuestions);
    console.log('待执行问句数量:', pendingQuestions ? pendingQuestions.length : 0);

    if (!pendingQuestions || pendingQuestions.length === 0) {
      alert('任务已全部完成');
      currentPendingTask = null;
      document.getElementById('current-task-name').textContent = '-';
      document.getElementById('execute-task-btn').disabled = true;
      return;
    }

    // 禁用按钮
    document.getElementById('execute-task-btn').disabled = true;
    document.getElementById('execute-task-btn').textContent = '执行中...';
    document.getElementById('task-progress-bar').style.display = 'block';

    const totalQuestions = pendingQuestions.length;
    console.log(`\n任务"${taskName}"有 ${totalQuestions} 个问句待执行`);

    // 2. 循环执行每个问句
    for (let i = 0; i < totalQuestions; i++) {
      const question = pendingQuestions[i];
      
      // ⭐ 添加详细日志，检查数据结构
      console.log(`\n========== 问句 ${i + 1}/${totalQuestions} ==========`);
      console.log('问句对象:', question);
      console.log('问句字段:', Object.keys(question));
      
      let { questionId, questionContent, pendingPlatforms } = question;
      
      console.log(`questionId: ${questionId}`);
      console.log(`questionContent: ${questionContent}`);
      console.log(`pendingPlatforms:`, pendingPlatforms);
      
      // ⭐ 验证数据完整性
      if (!questionId) {
        console.error('❌ questionId为空，跳过此问句');
        continue;
      }
      
      if (!questionContent) {
        console.error('❌ questionContent为空，尝试其他字段...');
        // 尝试其他可能的字段名
        questionContent = question.questionContent || question.content || question.question;
        console.log(`尝试获取内容: ${questionContent}`);
        
        if (!questionContent) {
          console.error('❌ 无法获取问句内容，跳过此问句');
          continue;
        }
      }
      
      if (!Array.isArray(pendingPlatforms) || pendingPlatforms.length === 0) {
        console.error('❌ pendingPlatforms为空，跳过此问句');
        continue;
      }

      console.log(`[${i + 1}/${totalQuestions}] 执行问句: ${questionContent}`);
      console.log(`待执行平台: ${pendingPlatforms.join(', ')}`);

      // 更新进度
      updateTaskProgress(i, totalQuestions, `执行问句 ${i + 1}/${totalQuestions}`);

      // 3. 在每个待执行的平台采集
      console.log(`\n🔄 开始平台循环，共 ${pendingPlatforms.length} 个平台`);
      console.log(`平台列表:`, pendingPlatforms);
      
      for (let platformIndex = 0; platformIndex < pendingPlatforms.length; platformIndex++) {
        const platform = pendingPlatforms[platformIndex];
        
        console.log(`\n========== [${platformIndex + 1}/${pendingPlatforms.length}] 准备执行平台: ${platform} ==========`);
        console.log(`  当前问句ID: ${questionId}`);
        console.log(`  当前问句内容: ${questionContent}`);
        console.log(`  时间: ${new Date().toLocaleTimeString()}`);
        console.log(`  popup页面状态: ${document.visibilityState}`);
        console.log(`  popup是否激活: ${document.hasFocus()}`);
        
        try {
          // 采集
          const startTime = Date.now();
          console.log(`  🚀 步骤1: 开始采集...`);
          console.log(`  即将调用 collectQuestionFromPlatform(${questionId}, "${questionContent.substring(0, 30)}...", "${platform}")`);
          
          const collectResult = await collectQuestionFromPlatform(questionId, questionContent, platform);
          
          const responseTime = Date.now() - startTime;
          console.log(`  ✅ 步骤1完成: 采集成功，耗时 ${responseTime}ms`);
          console.log(`  collectQuestionFromPlatform已返回`);
          
          console.log(`  采集完成，耗时: ${responseTime}ms`);
          console.log(`  采集结果对象:`, collectResult);
          console.log(`  采集结果详情:`, {
            hasResponse: !!collectResult.response,
            hasAnswer: !!(collectResult.response && collectResult.response.answer),
            answerLength: collectResult.response && collectResult.response.answer ? collectResult.response.answer.length : 0,
            answerPreview: collectResult.response && collectResult.response.answer ? collectResult.response.answer.substring(0, 100) + '...' : 'null'
          });

          // 上报结果
          console.log(`  🚀 步骤2: 开始上报结果到后端...`);
          
          // ⭐ 从collectResult.response中提取数据
          const responseData = collectResult.response || collectResult;
          
          console.log(`  上报数据:`, {
            taskId,
            questionId,
            platform,
            questionContent: questionContent,
            answerLength: responseData.answer ? responseData.answer.length : 0,
            hasHtml: !!responseData.answerHtml
          });
          
          await submitResultToBackend(taskId, questionId, platform, {
            questionContent,
            answerContent: responseData.answer || '',
            answerHtml: responseData.answerHtml || responseData.answer || '',
            responseTime,
            collectStatus: 'success'
          });

          console.log(`  ✅ 步骤2完成: 上报成功`);
          console.log(`========== 平台 ${platform} 执行完成 ==========\n`);
          console.log(`⏭️  [${platformIndex + 1}/${pendingPlatforms.length}] 平台执行完成`);
          console.log(`⏭️  popup状态: visible=${document.visibilityState}, focused=${document.hasFocus()}`);
          console.log(`⏭️  准备执行下一个平台...`);
          
          // ⭐ 强制等待，确保循环继续
          await new Promise(resolve => setTimeout(resolve, 100));
          console.log(`⏭️  已等待100ms，继续循环...`);

        } catch (error) {
          console.error(`========== 平台 ${platform} 执行失败 ==========`);
          console.error(`  ❌ 错误类型: ${error.name}`);
          console.error(`  ❌ 错误消息: ${error.message}`);
          console.error(`  ❌ 错误堆栈:`, error.stack);

          // 上报失败状态
          try {
            console.log(`  🚀 步骤2: 尝试上报失败状态...`);
            await submitResultToBackend(taskId, questionId, platform, {
              questionContent,
              collectStatus: 'failed',
              errorMessage: error.message || error.toString()
            });
            console.log(`  ✅ 步骤2完成: 失败状态已上报`);
          } catch (reportError) {
            console.error(`  ❌ 上报失败状态也失败了:`, reportError);
          }
          
          console.log(`========== 平台 ${platform} 处理完成（失败） ==========\n`);
          console.log(`⏭️  [${platformIndex + 1}/${pendingPlatforms.length}] 平台处理完成（失败）`);
          console.log(`⏭️  popup状态: visible=${document.visibilityState}, focused=${document.hasFocus()}`);
          console.log(`⏭️  继续下一个平台...`);
          
          // ⭐ 强制等待，确保循环继续
          await new Promise(resolve => setTimeout(resolve, 100));
          console.log(`⏭️  已等待100ms，继续循环...`);
        }
        
        console.log(`\n⏭️  [${platformIndex + 1}/${pendingPlatforms.length}] 循环迭代完成`);
        console.log(`⏭️  platformIndex: ${platformIndex}, 总数: ${pendingPlatforms.length}`);
        console.log(`⏭️  是否还有下一个平台: ${platformIndex + 1 < pendingPlatforms.length ? '是' : '否'}\n`);
      }
      
      console.log(`\n⏭️⏭️  所有平台执行完毕，准备执行下一个问句...\n`);
      
      console.log(`问句 ${i + 1}/${totalQuestions} 执行完成\n`);
    }

    // 4. 完成
    updateTaskProgress(totalQuestions, totalQuestions, '任务完成');
    
    console.log('\n========== 任务执行完成 ==========');
    console.log('任务名称:', taskName);
    console.log('总问句数:', totalQuestions);
    console.log('总平台数:', totalQuestions * pendingQuestions[0].pendingPlatforms.length);
    console.log('===================================\n');
    
    alert(`任务"${taskName}"执行完成！\n请刷新页面查看结果。`);

    // 重置状态
    currentPendingTask = null;
    document.getElementById('current-task-name').textContent = '-';
    document.getElementById('execute-task-btn').textContent = '执行任务';
    document.getElementById('task-progress-bar').style.display = 'none';
    
    // ⭐ 自动刷新任务列表，获取下一个待执行任务
    console.log('正在刷新任务列表...');
    setTimeout(() => {
      refreshTasks();
    }, 1000);

  } catch (error) {
    console.error('任务执行失败:', error);
    alert('任务执行失败: ' + error.message);
    
    // 重置按钮
    document.getElementById('execute-task-btn').disabled = false;
    document.getElementById('execute-task-btn').textContent = '执行任务';
  }
}

/**
 * 从指定平台采集问句
 */
async function collectQuestionFromPlatform(questionId, questionContent, platform) {
  console.log(`\n[collectQuestionFromPlatform] 开始采集`);
  console.log(`  平台: ${platform}`);
  console.log(`  问句ID: ${questionId}`);
  console.log(`  问句内容: ${questionContent}`);
  
  // 查找对应平台的标签页
  const tabs = await chrome.tabs.query({});
  console.log(`  找到的所有标签页数量: ${tabs.length}`);
  
  const platformUrls = {
    'deepseek': 'chat.deepseek.com',
    'yuanbao': 'yuanbao.tencent.com',
    'doubao': 'doubao.com'
  };

  const platformTab = tabs.find(tab => 
    tab.url && tab.url.includes(platformUrls[platform])
  );

  if (!platformTab) {
    console.error(`  ❌ 未找到${platform}平台的标签页`);
    console.error(`  期望URL包含: ${platformUrls[platform]}`);
    console.error(`  所有标签页URL:`, tabs.map(t => t.url));
    throw new Error(`未找到${platform}平台的标签页，请先打开对应页面`);
  }

  console.log(`  ✅ 找到${platform}标签页:`, {
    id: platformTab.id,
    url: platformTab.url,
    title: platformTab.title,
    active: platformTab.active,
    windowId: platformTab.windowId
  });

  // ⭐ 关键修复：激活标签页（切换到该标签页）
  try {
    console.log(`  正在激活标签页...`);
    await chrome.tabs.update(platformTab.id, { active: true });
    console.log(`  ✅ 标签页已激活`);
    
    // ⭐ 等待标签页切换完成
    await new Promise(resolve => setTimeout(resolve, 500));
    console.log(`  等待标签页加载完成...`);
  } catch (error) {
    console.error(`  ❌ 激活标签页失败:`, error);
    throw new Error(`激活${platform}标签页失败: ${error.message}`);
  }

  // 发送消息给content script
  return new Promise((resolve, reject) => {
    // ⭐ 获取当前任务ID
    const taskId = currentPendingTask ? currentPendingTask.taskId : 0;
    
    console.log(`  📤 准备发送消息给content script...`);
    console.log(`  标签页ID: ${platformTab.id}`);
    console.log(`  平台: ${platform}`);
    console.log(`  消息内容:`, {
      action: 'sendMessage',
      message: questionContent,
      taskId: taskId,
      questionId: questionId
    });
    
    // ⭐⭐⭐ 添加超时保护（3分钟）⭐⭐⭐
    let hasResponded = false;
    const timeoutId = setTimeout(() => {
      if (!hasResponded) {
        console.error(`  ❌❌❌ 超时：3分钟内未收到content script响应 ❌❌❌`);
        console.error(`  平台: ${platform}`);
        console.error(`  标签页ID: ${platformTab.id}`);
        hasResponded = true;
        reject(new Error(`${platform}平台采集超时（3分钟）`));
      }
    }, 180000);  // 3分钟
    
    try {
      console.log(`  ⏰ 设置超时保护: 3分钟`);
      
      chrome.tabs.sendMessage(platformTab.id, {
        action: 'sendMessage',
        message: questionContent,
        taskId: taskId,        // ⭐ 传递任务ID
        questionId: questionId  // ⭐ 传递问句ID
      }, (response) => {
        if (hasResponded) {
          console.warn(`  ⚠️ 响应已超时，忽略此响应`);
          return;
        }
        
        clearTimeout(timeoutId);
        hasResponded = true;
        
        console.log(`  📥 收到content script响应:`, response);
        console.log(`  响应时间: ${new Date().toLocaleTimeString()}`);
        
        if (chrome.runtime.lastError) {
          console.error(`  ❌ chrome.runtime.lastError:`, chrome.runtime.lastError);
          console.error(`  错误详情:`, {
            message: chrome.runtime.lastError.message,
            platform: platform,
            tabId: platformTab.id
          });
          reject(new Error(chrome.runtime.lastError.message));
          return;
        }

        if (response && response.success) {
          console.log(`  ✅ 响应成功，准备resolve`);
          resolve(response);
        } else {
          console.error(`  ❌ 响应失败或无响应:`, response);
          reject(new Error(response ? response.error : '采集失败'));
        }
      });
      
      console.log(`  ✅ chrome.tabs.sendMessage已调用（等待响应）`);
      console.log(`  等待时间: ${new Date().toLocaleTimeString()}`);
    } catch (error) {
      clearTimeout(timeoutId);
      hasResponded = true;
      console.error(`  ❌ 发送消息时发生异常:`, error);
      reject(error);
    }
  });
}

/**
 * 上报结果到后端
 */
async function submitResultToBackend(taskId, questionId, platform, result) {
  const settings = await chrome.storage.sync.get({ backendUrl: 'http://localhost:8080' });
  const apiUrl = settings.backendUrl + '/api/collect/submit';

  const data = {
    taskId,
    questionId,
    questionContent: result.questionContent,
    platform,
    answerContent: result.answerContent || '',
    answerHtml: result.answerHtml || '',
    collectTime: new Date().toISOString(),
    responseTime: result.responseTime || 0,
    collectStatus: result.collectStatus || 'success',
    errorMessage: result.errorMessage || null
  };

  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });

    const res = await response.json();
    if (res.code !== 200) {
      throw new Error(res.message || '上报失败');
    }

    console.log(`  ✓ 结果已上报`);
  } catch (error) {
    console.error('上报结果失败:', error);
    // 上报失败不中断执行
  }
}

/**
 * 更新任务进度
 */
function updateTaskProgress(current, total, message) {
  const percentage = total > 0 ? Math.round((current / total) * 100) : 0;
  
  document.getElementById('task-progress-text').textContent = `${current}/${total}`;
  document.getElementById('task-progress-fill').style.width = percentage + '%';
  
  console.log(`进度: ${current}/${total} (${percentage}%) - ${message}`);
}

